<template>
  <div>
    <el-form-item>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-if="state === undefined">新增</el-button>
      </el-col>
    </el-row>
  </el-form-item>
  <el-form>
    <el-table :loading="loading" :data="tableData" style="width: 98%">
      <el-table-column prop="goodsName" label="商品名称" />
      <el-table-column prop="primaryLocation" label="出库位置" />
      <el-table-column prop="allotLocation" label="调入位置" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-link type="primary" style="margin-right: 10px" v-if="state === undefined"
            @click="handleUp(scope.row)">修改</el-link>
          <el-link type="primary" style="margin-right: 10px" @click="del(scope.row.id)"
            v-if="state === undefined">删除</el-link>
          <el-link type="primary" style="margin-right: 10px" @click="update(scope.row)"
            v-if="states == 1 && state == 0 && scope.row.allotState == 0">调拨</el-link>
          <span v-if="scope.row.allotState == 1" class="el-tag el-tag--success el-tag--default el-tag--light">{{ "已调拨" }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="fetchData" />
  </el-form>

  <!-- 添加或修改调拨对话框 -->
  <el-dialog :close-on-click-modal="false" :title="title" v-model="open" width="500px" append-to-body>
    <el-form ref="allotRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="商品" prop="goodsNo">
        <el-select v-model="formData.goodsNo" placeholder="请输入商品">
          <el-option v-for="option in data.goodsOptions" :key="option.value" :label="option.label"
            :value="option.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="调入库区" prop="areaId">
        <el-select v-model="formData.areaId" placeholder="请选择调入库区" @change="onAreaChange">
          <el-option v-for="option in data.areaOptions" :key="option.value" :label="option.label"
            :value="option.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="调入货区" prop="shelfId">
        <el-select v-model="formData.shelfId" placeholder="请选择调入货架" @change="onShelfChange">
          <el-option v-for="option in data.shelfIdOptions" :key="option.value" :label="option.label"
            :value="option.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="调入货位" prop="locationId" >
        <el-select v-model="formData.locationId" placeholder="请选择调入货位">
          <el-option v-for="option in data.locationOptions" :key="option.value" :label="option.label"
            :value="option.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm(formData, title, rowId)">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>
<script setup>
import { reactive, ref } from "vue";
import request from "@/utils/request";
import { useRouter, useRoute } from "vue-router";
import tab from '@/plugins/tab'


const router = useRouter();
const { proxy } = getCurrentInstance();
const route = useRoute();
const documentValue = route.query.document;
const primaryWarehouseId = route.query.primaryWarehouseId;
const allotWarehouseId = route.query.allotWarehouseId;
const state = route.query.state;
const states = route.query.states;
let tableData = reactive([]);
let loading = ref(true);
const total = ref(0);
const open = ref(false);
const title = ref("");
let rowId = ref(null); // 存储当前行的 id
const window = globalThis;

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    goodsNo: [
      { required: true, message: '商品不能为空', trigger: ['change', 'blur'] }
    ],
    areaId: [
      { required: true, message: '库区不能为空', trigger: ['change', 'blur'] }
    ],
    shelfId: [
      { required: true, message: '货架不能为空', trigger: ['change', 'blur'] }
    ],
    locationId: [
      { required: true, message: '货位不能为空', trigger: ['change', 'blur'] }
    ],
    goodsOptions: [],
    areaOptions: [],
    shelfIdOptions: [],
    locationOptions: [],
  },
});

const { queryParams, rules } = toRefs(data);

// 调用查询库区名方法加载新增下拉框
async function selectgoods(title, goodsNo) {
  if (title === "添加调拨") {
    formData.goodsNo = null;
    loading.value = true;
    try {
      const resp = await request({
        url: "/goodsStore/store/select",
        method: "get",
        params: {
          allotState:0,
          warehouseId: primaryWarehouseId,
          status:0
        },
      });
      // 存储库区选项
      data.goodsOptions = resp.rows.map((item) => ({
        value: item.goodsNo,
        label: item.goodsNo + ":" + item.goodsName,
      }));
      loading.value = false;
      return resp;
    } catch (error) {
      loading.value = false;
      throw error;
    }
  } else if (title === "修改调拨") {
    loading.value = true;
    try {
      const resp = await request({
        url: "/goodsStore/store/selectup",
        method: "get",
        params: {
          goodsNo: goodsNo,
          allotState:0,
          warehouseId: primaryWarehouseId,
          status:0
        },
      });
      // 存储库区选项
      data.goodsOptions = resp.rows.map((item) => ({
        value: item.goodsNo,
        label: item.goodsNo + ":" + item.goodsName,
      }));
      loading.value = false;
      return resp;
    } catch (error) {
      loading.value = false;
      throw error;
    }
  }
}

// 调用查询库区名方法加载新增下拉框
async function selectArea() {
  loading.value = true;
  try {
    const resp = await request({
      url: "/area/area/selectByPid",
      method: "get",
      params: {
        id: allotWarehouseId,
      },
    });
    // 存储库区选项
    data.areaOptions = resp.rows.map((item) => ({
      value: item.id,
      label: item.name,
    }));
    loading.value = false;
    return resp;
  } catch (error) {
    loading.value = false;
    throw error;
  }
}

// 调用查询货架名方法加载新增下拉框
async function selectShelf(selectedValue, title) {
  data.shelfIdOptions = [];
  if (title === "添加调拨") {
    formData.shelfId = null;
    loading.value = true;
    try {
      const resp = await request({
        url: "/shelf/shelf/selectByPid",
        method: "get",
        params: {
          id: selectedValue,
        },
      });
      // 存储货架选项
      data.shelfIdOptions = resp.rows.map((item) => ({
        value: item.id,
        label: item.name,
      }));
      loading.value = false;
      return resp;
    } catch (error) {
      loading.value = false;
      throw error;
    }
  } else {
    loading.value = true;
    try {
      const resp = await request({
        url: "/shelf/shelf/selectByPid",
        method: "get",
        params: {
          id: selectedValue,
        },
      });
      // 存储货架选项
      data.shelfIdOptions = resp.rows.map((item) => ({
        value: item.id,
        label: item.name,
      }));
      loading.value = false;
      return resp;
    } catch (error) {
      loading.value = false;
      throw error;
    }
  }
}

// 调用查询货位名方法加载新增下拉框
async function selectLocation(selectedValue, title, id) {
  data.locationOptions = [];
  if (title === "修改调拨") {
    loading.value = true;
    try {
      const resp = await request({
        url: "/location/location/selectup",
        method: "get",
        params: {
          id: id,
          shelfId: selectedValue,
        },
      });
      // 存储货位选项
      data.locationOptions = resp.rows.map((item) => ({
        value: item.id,
        label: item.locationNo,
      }));
      loading.value = false;
      return resp;
    } catch (error) {
      loading.value = false;
      throw error;
    }
  } else {
    loading.value = true;
    try {
      const resp = await request({
        url: "/location/location/select",
        method: "get",
        params: {
          shelfId: selectedValue,
          status:1
        },
      });
      // 存储货位选项
      data.locationOptions = resp.rows.map((item) => ({
        value: item.id,
        label: item.locationNo,
      }));
      loading.value = false;
      return resp;
    } catch (error) {
      loading.value = false;
      throw error;
    }
  }
}

let formData = reactive({
  document: documentValue,
  primaryWarehouseId: primaryWarehouseId,
  allotWarehouseId: allotWarehouseId,
  goodsNo: null,
  areaId: null,
  shelfId: null,
  locationId: null,
});

function fetchData() {
  loading.value = true;
  request({
    url: "/allot/select",
    method: "get",
    params: {
      document: documentValue,
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize,
    },
  })
  .then((resp) => {
      loading.value = false;
      const data = resp.rows;
      tableData = data;
      total.value = resp.total;
      let num = 0;
      for (let i = 0; i < tableData.length; i++) {
        if (tableData[i].allotState === 1) {
          num++;
        }
      }
      if (num === tableData.length && tableData.length > 0) {
        upState(documentValue);
      }
    });
}

function del(id) {
  proxy.$modal.confirm("是否删除该订单").then(function () {
    request({
      url: "/allot/del",
      method: "delete",
      params: {
        id: id,
      },
    });
  }).then(() => {
    fetchData();
    reset();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 新增按钮操作 */
function handleAdd() {
  // 重置四个下拉框
  formData.goodsNo = null;
  formData.areaId = null;
  formData.shelfId = null;
  formData.locationId = null;
  data.goodsOptions = [];
  data.areaOptions = [];
  data.shelfIdOptions = [];
  data.locationOptions = [];

  open.value = true;
  title.value = "添加调拨";
  // 新增时加载库区、货架、货位下拉选项
  reset();
  selectgoods(title.value);
  selectArea();
}

/** 修改按钮操作 */
async function handleUp(row) {
  open.value = true;
  title.value = "修改调拨";
  rowId.value = row.id; // 设置当前行的 id

  // 根据 id 找到对应的行数据，并回填到表单中
  const rowToEdit = tableData.find((r) => r.id === row.id);
  if (rowToEdit) {
    formData.goodsNo = rowToEdit.goodsNo;
    await selectgoods(title.value, row.goodsNo);
    formData.areaId = rowToEdit.areaId;
    await selectArea();
    formData.shelfId = rowToEdit.shelfId;
    await selectShelf(formData.areaId);
    formData.locationId = rowToEdit.locationId;
    await selectLocation(formData.shelfId, title.value, formData.locationId);
  }
}

// 取消按钮
function cancel() {
  window.close();
  reset();
  open.value = false;
  // 重置表格
  fetchData();
}

function submitForm(form, title, id) {
  proxy.$refs["allotRef"].validate(valid => {
    if (!valid) {
      return;
    }
    if (title === "添加调拨") {
      form.id = null;
      request({
        url: "/allot/add",
        method: "post",
        data: form,
      })
      .then((response) => {
          fetchData();
          cancel();
          proxy.$modal.msgSuccess("新增成功");
        });
    } else if (title === "修改调拨") {
      form.id = id; // 将行的 id 添加到表单数据中
      request({
        url: "/allot/up",
        method: "put",
        data: form,
      })
      .then((response) => {
          fetchData();
          cancel();
          proxy.$modal.msgSuccess("修改成功");
        });
    }
  });
}

function reset() {
  formData.goodsNo = null;
  formData.areaId = null;
  formData.shelfId = null;
  formData.locationId = null;
  proxy.resetForm("allotRef");
}

// 库区选择变化时的处理函数
function onAreaChange(selectedValue, title) {
  formData.shelfId = null;
  data.shelfIdOptions=[]
  formData.locationId = null;
  data.locationOptions=[]
  selectShelf(selectedValue, title);
}

// 库区选择变化时的处理函数
function onShelfChange(selectedValue) {
  formData.locationId = null;
  data.locationOptions=[]
  selectLocation(selectedValue);
}


async function update(row) {
  const no = {
    goodsNo: row.goodsNo
  }
  await request({
    url: '/goodsStore/store/list',
    method: 'get',
    params:no
  }).then((resp) => {
    const i3={
      document:row.document,
      goodNo:row.goodsNo,
      primaryWarehouseId:resp.rows[0].warehouseId,
      primaryAreaId:resp.rows[0].areaId,
      primaryShelfId:resp.rows[0].shelfId,
      primaryLocationId:resp.rows[0].locationId,
    }
    request({
    url: '/inventory/record',
    method: 'post',
    data: i3
  })
    
    const i1={
    status:0,
    id:resp.rows[0].locationId
  }
  request({
    url: '/location/location',
    method: 'put',
    data: i1
  })
  })
  
  const data = {
    goodsNo: row.goodsNo,
    warehouseId: row.allotWarehouseId,
    areaId: row.areaId,
    shelfId: row.shelfId,
    locationId: row.locationId,
  };
  request({
    url: "/goodsStore/store",
    method: "put",
    data: data,
  });

  const form = {
    id: row.id,
    allotState: 1,
  };
  request({
    url: "/allot/up",
    method: "put",
    data: form,
  });


  const i2={
    status:1,
    id:row.locationId
  }
  request({
    url: '/location/location',
    method: 'put',
    data: i2
  })
  
  
  fetchData();
  proxy.$modal.msgSuccess("调拨成功");
}

async function upState(documentValue) {
  const xg = {
    allotState: 2,
    document: documentValue,
  };
  await request({
    url: "/allot/allot",
    method: "put",
    data: xg,
  });
  tab.closePage()
  router.push("/inventory/inventory")
}

fetchData();
</script>

<style scoped>
.el-table {
  margin: auto;
}
</style>